package com.ruoyi.jihuo.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmProductsOnSale;
import com.ruoyi.jihuo.mapper.JhTmProductsOnSaleMapper;
import com.ruoyi.jihuo.quzrtz.ClearZeroItem;
import com.ruoyi.jihuo.service.IJhTmAccountService;
import com.ruoyi.jihuo.service.IJhTmProductsOnSaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 在售商品Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-07
 */
@Service
@Slf4j
public class JhTmProductsOnSaleServiceImpl implements IJhTmProductsOnSaleService {
    @Autowired
    private JhTmProductsOnSaleMapper jhTmProductsOnSaleMapper;

    @Autowired
    private IJhTmAccountService jhTmAccountService;

    @Autowired
    private ClearZeroItem clearZeroItem;

    @Autowired
    private CallTaoApiService callTaoApiService;

    /**
     * 查询在售商品
     *
     * @param jhId 在售商品主键
     * @return 在售商品
     */
    @Override
    public JhTmProductsOnSale selectJhTmProductsOnSaleByJhId(Long jhId) {
        return jhTmProductsOnSaleMapper.selectJhTmProductsOnSaleByJhId(jhId);
    }

    /**
     * 查询在售商品列表
     *
     * @param jhTmProductsOnSale 在售商品
     * @return 在售商品
     */
    @Override
    public List<JhTmProductsOnSale> selectJhTmProductsOnSaleList(JhTmProductsOnSale jhTmProductsOnSale) {
        return jhTmProductsOnSaleMapper.selectJhTmProductsOnSaleList(jhTmProductsOnSale);
    }

    /**
     * 新增在售商品
     *
     * @param jhTmProductsOnSale 在售商品
     * @return 结果
     */
    @Override
    public int insertJhTmProductsOnSale(JhTmProductsOnSale jhTmProductsOnSale) {
        return jhTmProductsOnSaleMapper.insertJhTmProductsOnSale(jhTmProductsOnSale);
    }

    /**
     * 批量新增在售商品
     *
     * @param jhTmProductsOnSaleList 在售商品列表
     * @return 结果
     */
    @Override
    public int insertJhTmProductsOnSaleBatch(List<JhTmProductsOnSale> jhTmProductsOnSaleList) {
        if (jhTmProductsOnSaleList == null || jhTmProductsOnSaleList.size() == 0) {
            return 0;
        }
        return jhTmProductsOnSaleMapper.insertJhTmProductsOnSaleBatch(jhTmProductsOnSaleList);
    }

    /**
     * 修改在售商品
     *
     * @param jhTmProductsOnSale 在售商品
     * @return 结果
     */
    @Override
    public int updateJhTmProductsOnSale(JhTmProductsOnSale jhTmProductsOnSale) {
        return jhTmProductsOnSaleMapper.updateJhTmProductsOnSale(jhTmProductsOnSale);
    }

    /**
     * 批量删除在售商品
     *
     * @param jhIds 需要删除的在售商品主键
     * @return 结果
     */
    @Override
    public int deleteJhTmProductsOnSaleByJhIds(Long[] jhIds) {
        return jhTmProductsOnSaleMapper.deleteJhTmProductsOnSaleByJhIds(jhIds);
    }

    /**
     * 删除在售商品信息
     *
     * @param jhId 在售商品主键
     * @return 结果
     */
    @Override
    public int deleteJhTmProductsOnSaleByJhId(Long jhId) {
        return jhTmProductsOnSaleMapper.deleteJhTmProductsOnSaleByJhId(jhId);
    }

    @Override
    public int clear() {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            throw new RuntimeException("管理员无法执行此操作");
        }

        QueryWrapper<JhTmProductsOnSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("jhSalesVolume", 0);

        List<JhTmAccount> jhTmAccounts = jhTmAccountService.selectAllJhTmAccountList();
        Map<Long, JhTmAccount> accountMap = jhTmAccounts.stream()
                .collect(Collectors.toMap(JhTmAccount::getJhId, account -> account));
        queryWrapper.in("jhTmAccountId", accountMap.keySet());

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime sevenDaysAgo = now.minusDays(7);
        Date nowDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        Date sevenDaysAgoDate = Date.from(sevenDaysAgo.atZone(ZoneId.systemDefault()).toInstant());
        queryWrapper.between("jhListingTime", sevenDaysAgoDate, nowDate);

        List<JhTmProductsOnSale> onSaleList = jhTmProductsOnSaleMapper.selectList(queryWrapper);
        List<JSONObject> jsonObjectList = onSaleList.stream().map(item -> {
            JSONObject obj = new JSONObject();
            obj.put("item", item.getJhItemId()); // 自动转为 JSON 结构
            obj.put("account", accountMap.get(item.getJhTmAccountId())); // 从 Map 中取 Account
            return obj;
        }).collect(Collectors.toList());

        clearZeroItem.getQueue().addAll(jsonObjectList);
        return 0;
    }

    @Override
    public void syncVolume() {
        List<JhTmAccount> jhTmAccounts = jhTmAccountService.selectAllJhTmAccountList();
        for (JhTmAccount jhTmAccount : jhTmAccounts) {
            getItemsOnSaleUntilZero(jhTmAccount);
        }
    }

    @Override
    public boolean isExistByJhTmAccountIdAndJhOriginalUrl(Long accountId, String jhOriginalUrl) {
        LambdaQueryWrapper<JhTmProductsOnSale> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JhTmProductsOnSale::getJhTmAccountId, accountId);
        wrapper.eq(JhTmProductsOnSale::getJhOriginalUrl, jhOriginalUrl);
        wrapper.eq(JhTmProductsOnSale::getJhStatus, "2");
        Integer count = jhTmProductsOnSaleMapper.selectCount(wrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Map<Long, JhTmProductsOnSale> selectMapByTaskIdAndStatus(Long jhTaskId, String status) {
        LambdaQueryWrapper<JhTmProductsOnSale> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JhTmProductsOnSale::getJhTaskId, jhTaskId);
        wrapper.eq(JhTmProductsOnSale::getJhStatus, status);
        List<JhTmProductsOnSale> list = jhTmProductsOnSaleMapper.selectList(wrapper);
        Map<Long, JhTmProductsOnSale> resultMap = list.stream()
                .collect(Collectors.toMap(
                        JhTmProductsOnSale::getJhGoodId,  // 指定key为jhGoodId字段
                        item -> item    // value为对象本身
                ));

        return resultMap;
    }

    @Override
    public void updateBatch(List<JhTmProductsOnSale> productsOnSales) {
        for (JhTmProductsOnSale productsOnSale : productsOnSales) {
            jhTmProductsOnSaleMapper.updateById(productsOnSale);
        }
    }

    /**
     * 根据天猫账号查询所有商品，直到找到销量为0的商品为止
     * @param jhTmAccount 天猫账号
     */
    public void getItemsOnSaleUntilZero(JhTmAccount jhTmAccount) {
        Long pageNo = 1L;
        int queryCount = 0; // 查询次数
        
        while (true) {
            queryCount++;
            JSONArray itemsOnSale = callTaoApiService.getItemsOnSale(jhTmAccount, pageNo, "sold_quantity:desc");
            
            // 记录查询次数
            log.info("查询天猫账号 {} 的第 {} 页商品，总查询次数: {}", jhTmAccount.getJhAccount(), pageNo, queryCount);
            
            // 如果没有商品数据，则退出循环
            if (itemsOnSale == null || itemsOnSale.isEmpty()) {
                break;
            }
            
            // 检查最后一条数据的销量
            JSONObject lastItem = itemsOnSale.getJSONObject(itemsOnSale.size() - 1);
            long soldQuantity = Long.parseLong(lastItem.getString("sold_quantity"));
            
            // 如果销量为0，则退出循环
            if (soldQuantity == 0) {
                log.info("在第 {} 次查询中找到销量为0的商品，停止查询", queryCount);
                break;
            }
            
            // 继续查询下一页
            pageNo++;
        }
        
        log.info("天猫账号 {} 查询完成，总共查询 {} 次", jhTmAccount.getJhAccount(), queryCount);
    }
}

